'use strict'

const {ERROR} = require("../util/util");
const Service = require('egg').Service
const path = require('path')
const fs = require('fs')

class UploadService extends Service {
    // 上传单个文件
    async create(payload) {
        return this.ctx.model.Attachment.create(payload)
    }

    // 删除单个文件
    async destroy(_id) {
        const {ctx, service} = this
        const res = await ctx.service.upload.find(_id)
        const attachment = res.dataValues

        if (!attachment) {
            ctx.throw(404, 'attachment not found')
        } else {
            const target = path.join(this.config.baseDir, 'app/public/uploads', `${attachment.filename}${attachment.extname}`)
            fs.unlinkSync(target)
        }
        return ctx.model.Attachment.destroy({
            where: {
                id: _id
            }
        })
    }

    //根据id查早当前文件
    async find(id) {
        return this.ctx.model.Attachment.findOne({
            where: {
                id
            },
        })
    }
}

module.exports = UploadService
